import argparse
import re


# 统一文件读取函数（集中处理文件相关异常）
def read_file_safely(filename):
    """
    安全读取文件内容，处理常
    见文件异常
    :param filename: 文件名
    :return: 文件内容（字符串）
    :raises: 捕获异常后主动退出程序，避免后续逻辑出错
    """
    try:
        with open(filename, 'r', encoding='utf-8') as f:
            return f.read()
    except FileNotFoundError:
        print(f"错误：文件 '{filename}' 不存在，请检查路径和文件名是否正确。")
        exit(1)
    except PermissionError:
        print(f"错误：没有读取文件 '{filename}' 的权限，请检查文件权限设置。")
        exit(1)
    except UnicodeDecodeError:
        print(f"错误：文件 '{filename}' 不是UTF-8编码，无法读取。请转换为UTF-8编码后重试。")
        exit(1)
    except Exception as e:
        print(f"错误：读取文件时发生意外错误 - {str(e)}")
        exit(1)

parser = argparse.ArgumentParser(description='文本计数统计程序')
parser.add_argument('-c', action='store_true', help='统计字符数')
parser.add_argument('-w', action='store_true', help='统计单词数')
parser.add_argument('-s', action='store_true', help='统计句子数')
parser.add_argument('-l', action='store_true', help='统计代码行数（非空非注释行）')
parser.add_argument('-e', action='store_true', help='统计空行数')
parser.add_argument('-cmt', action='store_true', help='统计注释行数（以#开头的行）')
parser.add_argument('filename', help='要统计的文本文件名')
args = parser.parse_args()

def count_chars(filename):
    content = read_file_safely(filename)
    return len(content)

def count_words(filename):
    content = read_file_safely(filename)
    words = re.findall(r'[a-zA-Z]+', content)
    return len(words)


def count_sentences(filename):
    content = read_file_safely(filename)
    sentences = re.split(r'[.!?]+', content)
    return len([s for s in sentences if s.strip()])



def count_code_lines(filename):
    code_lines = 0
    try:
        with open(filename, 'r', encoding='utf-8') as f:
            for line in f:
                line_strip = line.strip()
                if line_strip and not line_strip.startswith('#'):
                    code_lines += 1
    except Exception as e:
        print(f"错误：统计代码行时发生错误 - {str(e)}")
        exit(1)
    return code_lines


def count_empty_lines(filename):
    empty_lines = 0
    try:
        with open(filename, 'r', encoding='utf-8') as f:
            for line in f:
                if not line.strip():
                    empty_lines += 1
    except Exception as e:
        print(f"错误：统计空行时发生错误 - {str(e)}")
        exit(1)
    return empty_lines


def count_comment_lines(filename):
    comment_lines = 0
    try:
        with open(filename, 'r', encoding='utf-8') as f:
            for line in f:
                line_strip = line.strip()
                if line_strip.startswith('#'):
                    comment_lines += 1
    except Exception as e:
        print(f"错误：统计注释行时发生错误 - {str(e)}")
        exit(1)
    return comment_lines



if args.c:
    print(f"字符数: {count_chars(args.filename)}")
if args.w:
    print(f"单词数: {count_words(args.filename)}")
if args.s:
    print(f"句子数：{count_sentences(args.filename)}")
if args.l:
    print(f"代码行数：{count_code_lines(args.filename)}")
if args.e:
    print(f"空行数：{count_empty_lines(args.filename)}")
if args.cmt:
    print(f"注释行数：{count_comment_lines(args.filename)}")
